package cn.zyy.jdbc;

import cn.zyy.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 解决SQL注入问题
 */
public class JDBCDemo03 {
    public static void main(String[] args) {
        Connection conn = JDBCUtil.getConnection();
        PreparedStatement pstmt =null;
        ResultSet rs = null;
        //获取prepareStatement对象时  要对SQL语句进行预编译  相同的操作不会重复的编译  提高效率
        String sql = "select username,password from usr where id = ?";
        try {
            pstmt = conn.prepareStatement(sql);//sql预编译
            //设置参数  参数1：设置参数的索引 (第几个参数)  参数2：设置的参数值
            pstmt.setInt(1,1);
            //执行sql
            rs = pstmt.executeQuery();
            while(rs.next()) {
                String username = rs.getString("username");
                String password = rs.getString("password");
                System.out.println("username:"+username+"\tpassword:"+password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.closeAll(rs,pstmt,conn);
        }
    }
}
